import { useRef } from 'react';

import { useRequest } from 'ahooks';
import { Button, Col, Form, Popconfirm, Row, Space, Tooltip } from 'antd';

import Text from '@/components/text';

import { store } from '@/store';

import {
  systemConfigDelete,
  systemConfigList,
  systemConfigSet
} from '@/services/base/jichumokuaixitongpeizhixinxijiekou';
import { Icon } from '@iconify/react';

import Control from './control';
import Edit, { EditRef } from './edit';

export type PanelProps = {
  group: BASE.SysWebSystemConfigGroupVO;
};

const Panel: React.FC<PanelProps> = ({ group }) => {
  const [form] = Form.useForm();
  const edit = useRef<EditRef>(null);
  const config = useRequest(async () => {
    const res = await systemConfigList({
      configModule: group.groupName
    } as ArgumentsType<typeof systemConfigList>[0]);

    return res.data;
  });
  const submit = useRequest(
    async (values: ArgumentsType<typeof systemConfigSet>[0]) => {
      const res = await systemConfigSet(values);

      config.refresh();

      store.app?.message.success('保存成功');
      emitDevice();
      return res.data;
    },
    {
      manual: true
    }
  );

  // 通知终端
  const emitDevice = () => {
    store.getConfig();
    // viewStore.deviceList?.forEach(device => {
    //   viewSocket?.emit('device_control', JSON.stringify({
    //     devIdList: [device.devId],
    //     action: 'config-update'
    //   }))
    // })
  };

  return (
    <>
      <div
        style={{
          marginBottom: 24
        }}
      >
        <Button
          onClick={() => {
            edit.current?.open({
              groupData: group,
              type: 'add',
              onSuccess: () => {
                config.refresh();
                emitDevice();
              }
            });
          }}
        >
          新增字段
        </Button>
      </div>

      <Form
        layout="horizontal"
        onFinish={async (values) => {
          const list = Object.entries(values).map((v) => ({
            id: v[0] as unknown as number,
            value: String(v[1])
          }));
          submit.run({
            list
          } as unknown as ArgumentsType<typeof systemConfigSet>[0]);
        }}
        form={form}
        labelWrap
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        disabled={config.loading || submit.loading}
      >
        <Row gutter={[16, 16]}>
          {config.data?.map((item) => {
            const rules: React.ComponentProps<typeof Form.Item>['rules'] = [];

            if (item.configCheckRegular) {
              rules.push({
                pattern: new RegExp(item.configCheckRegular),
                message: item.configExplain || `请输入正确的${item.configName}`
              });
            }

            return (
              <Col key={item.id} xs={24} sm={24} md={12} lg={12} xl={8} xxl={8}>
                <Form.Item
                  key={item.id}
                  name={item.id}
                  label={
                    <div>
                      {item.configExplain ? (
                        <Tooltip title={item.configExplain}>
                          <Icon
                            icon="ri-information-line"
                            style={{
                              marginRight: 4,
                              fontSize: 16,
                              color: '#999',
                              verticalAlign: -3,
                              cursor: 'pointer'
                            }}
                          />
                        </Tooltip>
                      ) : null}
                      <span>{item.configName}</span>
                    </div>
                  }
                  initialValue={item.configValue}
                  extra={
                    <Text.Space>
                      <Text
                        onClick={() => {
                          edit.current?.open({
                            groupData: group,
                            rowData: item,
                            type: 'edit',
                            onSuccess: () => {
                              config.refresh();
                              emitDevice();
                            }
                          });
                        }}
                      >
                        编辑
                      </Text>
                      <Popconfirm
                        title={`确定删除该吗？`}
                        onConfirm={async () => {
                          const res = await systemConfigDelete({
                            id: item.id as unknown as string
                          });

                          store.app?.message.success(res.message);
                          config.refresh();
                          emitDevice();

                          return res.success;
                        }}
                      >
                        <Text type="danger">删除</Text>
                      </Popconfirm>
                    </Text.Space>
                  }
                  rules={rules}
                >
                  <Control settingType={item.configType} placeholder={item.configName} />
                </Form.Item>
              </Col>
            );
          })}
        </Row>

        <Space>
          <Button
            loading={submit.loading}
            disabled={config.loading || submit.loading}
            type="primary"
            htmlType="submit"
          >
            保存
          </Button>
        </Space>
      </Form>

      <Edit ref={edit} />
    </>
  );
};

export default Panel;
